#include "socket_server.h"
#include <iostream>
#include <string>
#include <thread>

int main()
{
    SocketServer server;

    // 初始化并启动服务器
    if (!server.start(18843))
    {
        std::cerr << "启动服务器失败" << std::endl;
        return 1;
    }

    // 设置消息回调
    server.setMessageCallback([&server](const std::string &client_id, const std::string &message)
                              {
        std::cout << "收到来自 " << client_id << " 的消息: " << message << std::endl;
        
        // 可以根据需要回复消息
        server.sendMessage("Echo: " + message, client_id); });

    // 设置客户端连接回调
    server.setClientConnectCallback([](const std::string &client_id)
                                    { std::cout << "客户端已连接: " << client_id << std::endl; });

    // 设置客户端断开连接回调
    server.setClientDisconnectCallback([](const std::string &client_id)
                                       { std::cout << "客户端已断开: " << client_id << std::endl; });

    // 主线程用于控制台交互
    std::string input, target;
    while (true)
    {
        std::cout << "输入客户端ID (或输入 'all' 广播消息, 'list' 列出客户端, 'exit' 退出): ";
        std::getline(std::cin, target);

        if (target == "exit")
            break;

        if (target == "list")
        {
            // 列出所有客户端
            auto clients = server.getClientIds();
            std::cout << "已连接的客户端: ";
            if (clients.empty())
            {
                std::cout << "无" << std::endl;
            }
            else
            {
                for (const auto &id : clients)
                {
                    std::cout << id << " ";
                }
                std::cout << std::endl;
            }
            continue;
        }

        std::cout << "输入消息内容: ";
        std::getline(std::cin, input);

        if (target == "all")
        {
            server.broadcastMessage(input);
            std::cout << "消息已广播" << std::endl;
        }
        else
        {
            if (server.sendMessage(input, target))
            {
                std::cout << "消息已发送到 " << target << std::endl;
            }
            else
            {
                std::cerr << "发送消息失败" << std::endl;
            }
        }
    }

    server.stop();
    return 0;
}